import logging
import os.path
import time

import colorlog

from settings import ROOT_PATH
from utils.config import Config


class Log:
    log_conf = Config().get_log_config()

    def __init__(self):
        self._logger = logging.getLogger()

    @property
    def logfile(self):
        logdir = self.log_conf.get('log_dir')
        logdir = os.path.join(ROOT_PATH, logdir)
        if not os.path.exists(logdir):
            os.mkdir(logdir)
        now = time.strftime('%Y-%m-%d_%H-%M-%S')
        return os.path.join(logdir, f'{now}.log')

    def console_handler(self):
        sh = colorlog.StreamHandler()
        fmt = colorlog.ColoredFormatter(fmt=self.log_conf.get('log_cli_format'),
                                        datefmt=self.log_conf.get('log_cli_date_format'))
        sh.setFormatter(fmt)
        level = self.log_conf.get('log_cli_level')
        level = logging.getLevelName(level.upper())
        sh.setLevel(level)
        return sh

    def file_handler(self):
        fh = logging.FileHandler(filename=self.logfile,
                                 mode='a',
                                 encoding='utf-8')
        fmt = logging.Formatter(fmt=self.log_conf.get('log_file_format'),
                                datefmt=self.log_conf.get('log_file_date_format'))
        fh.setFormatter(fmt)
        level = self.log_conf.get('log_file_level')
        level = logging.getLevelName(level.upper())
        fh.setLevel(level)
        return fh

    @property
    def logger(self):
        if self._logger.handlers:
            return self._logger

        if self.log_conf.get('log_cli'):
            sh = self.console_handler()
            self._logger.addHandler(sh)

        fh = self.file_handler()
        self._logger.addHandler(fh)
        self._logger.setLevel(logging.NOTSET)
        return self._logger


logger = Log().logger

if __name__ == '__main__':
    logger.debug('This ia a log.')
